package design;

import java.util.HashMap;
import java.util.Map;

public class Client {

    interface IFlyweight{
        void operation(String extrinsicState);
    }


    //具体享元角色
    static class ConcreteFlyweight implements IFlyweight{
        private String intrinsicState;

        public ConcreteFlyweight(String intrinsicState){
            this.intrinsicState = intrinsicState;
        }

        public void operation(String extrinsicState){
            System.out.println("Object address:" + System.identityHashCode(this));
            System.out.println("IntrinsicState:" + this.intrinsicState);
            System.out.println("ExtrinsicState:" + extrinsicState);
        }


    }

    //享元工厂
    static class FlyweightFactory{
        private static Map<String,IFlyweight> pool = new HashMap<String,IFlyweight>();

        public static IFlyweight getFlyweight(String intrinsicState){
            if(!pool.containsKey(intrinsicState)){
                IFlyweight flyweight = new ConcreteFlyweight(intrinsicState);
                pool.put(intrinsicState,flyweight);
                return flyweight;
            }
            return pool.get(intrinsicState);
        }
    }
}
